import { useState, useCallback, useMemo } from 'react'

export interface FilterConfig<T> {
  [key: string]: (item: T, value: any) => boolean
}

/**
 * useFilter Hook
 * 数据筛选管理
 */
export const useFilter = <T extends Record<string, any>>(
  data: T[],
  filterConfig: FilterConfig<T> = {}
) => {
  const [filters, setFilters] = useState<Record<string, any>>({})

  /**
   * 设置筛选条件
   */
  const setFilter = useCallback((key: string, value: any) => {
    setFilters((prev) => ({
      ...prev,
      [key]: value,
    }))
  }, [])

  /**
   * 批量设置筛选条件
   */
  const setMultipleFilters = useCallback((newFilters: Record<string, any>) => {
    setFilters((prev) => ({
      ...prev,
      ...newFilters,
    }))
  }, [])

  /**
   * 移除筛选条件
   */
  const removeFilter = useCallback((key: string) => {
    setFilters((prev) => {
      const newFilters = { ...prev }
      delete newFilters[key]
      return newFilters
    })
  }, [])

  /**
   * 重置所有筛选条件
   */
  const resetFilters = useCallback(() => {
    setFilters({})
  }, [])

  /**
   * 筛选后的数据
   */
  const filteredData = useMemo(() => {
    if (Object.keys(filters).length === 0) {
      return data
    }

    return data.filter((item) => {
      return Object.keys(filters).every((key) => {
        const filterValue = filters[key]

        // 跳过空值筛选
        if (filterValue === undefined || filterValue === null || filterValue === '') {
          return true
        }

        // 使用自定义筛选函数
        if (filterConfig[key]) {
          return filterConfig[key](item, filterValue)
        }

        // 默认筛选逻辑：严格相等
        return item[key] === filterValue
      })
    })
  }, [data, filters, filterConfig])

  // 派生状态
  const hasFilters = useMemo(() => {
    return Object.keys(filters).some((key) => {
      const value = filters[key]
      return value !== undefined && value !== null && value !== ''
    })
  }, [filters])

  const filterCount = useMemo(() => {
    return Object.keys(filters).filter((key) => {
      const value = filters[key]
      return value !== undefined && value !== null && value !== ''
    }).length
  }, [filters])

  return {
    // 状态
    filters,
    filteredData,
    hasFilters,
    filterCount,
    resultCount: filteredData.length,

    // 方法
    setFilter,
    setMultipleFilters,
    removeFilter,
    resetFilters,
  }
}

export default useFilter

